<template>
  <div>
    <el-button
      type="primary"
      :loading="loadData.field"
      @click="submitRepairField()"
      :disabled="props.isDisabled"
      >更新字段数据</el-button
    >
    <el-button
      type="primary"
      :loading="loadData.field"
      @click="submitRepairFieldByContent()"
      :disabled="props.isDisabled"
      >更新content字段数据</el-button
    >
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { getRepairList, getRepairDetail, updateRepair } from '@/apis/repair';
import { getAttrValByHtml } from '@/utils/util';

const dbname = 'goods';

// props
const props = defineProps({
  isDisabled: {
    type: Boolean,
    default: false
  }
});

const loadData = reactive({
  goodsDB: false,
  field: false
});

/**
 * 更新商品字段
 */
const submitRepairField = async (page: number = 1) => {
  loadData.field = true;

  // 每次取20条数据
  const maxLimit = 20;
  const resList = await getRepairList<{ id: number }[]>(dbname, {
    page,
    limit: maxLimit
  });

  if (!resList.data.data || !resList.data.data.length) {
    console.warn('执行结束');
    loadData.field = false;
    return;
  }

  // 循环所有数据
  for (let i = 0; i < resList.data.data.length; i++) {
    const item = resList.data.data[i];

    const res = await getRepairDetail<API.goods.EntitySchema>(dbname, item.id!);

    // 判断是否需要修改
    let judge = false;
    const dataOpt: any = {};

    console.group('更新商品字段');
    console.log(
      `[Limit] - ${maxLimit} -- [Page] - ${page} -- [Current] - ${i + 1}`
    );
    console.log(`[ID] - ${res.data.id}`);
    console.log(`[ownId] - ${res.data.ownId}`);
    console.log(`[title] - ${res.data.title}`);
    console.log(`--------更新字段--------`);

    // 检查数据是否正常
    if (res.data.albums && /^\/upload/.test(res.data.albums!) === false) {
      console.log(`[albums - Raw] - ${res.data.albums}`);
      // 若数据不正确，则进行格式化
      dataOpt.albums =
        res.data
          .albums!.match(/images(.*?)(jpg|png)/gi)
          ?.map((item) => {
            return /\/upload\/attachment/.test(item)
              ? item
              : '/upload/attachment/' + item;
          })
          .join(',') || '';

      // 两次不同，则需要修改
      judge = true;
      console.log(`[albums - New] - ${dataOpt.albums}`);
    }

    // 检查数据是否正常
    if (res.data.cover && /^\/upload/.test(res.data.cover!) === false) {
      console.log(`[cover - Raw] - ${res.data.cover}`);
      dataOpt.cover = '/upload/attachment/' + res.data.cover;
      console.log(`[cover - New] - ${dataOpt.cover}`);
      // 两次不同，则需要修改
      judge = true;
    }

    // 检查数据是否正常
    if (res.data.video && /^\/upload/.test(res.data.video!) === false) {
      console.log(`[video - Raw] - ${res.data.video}`);
      dataOpt.video = '/upload/attachment/' + res.data.video;
      console.log(`[video - New] - ${dataOpt.video}`);
      // 两次不同，则需要修改
      judge = true;
    }

    console.groupEnd();

    if (!judge) continue;

    try {
      await updateRepair(dbname, res.data.id!, dataOpt);
    } catch (error) {
      console.error('submitRepairFieldByContent', error);
      loadData.field = false;
      return;
    }
  }

  setTimeout(() => {
    submitRepairField(page + 1);
  }, 2 * 1000);
};

/**
 * 更新商品字段 - content字段
 */
const submitRepairFieldByContent = async (page: number = 1) => {
  loadData.field = true;

  // 每次取20条数据
  const maxLimit = 20;
  const resList = await getRepairList(dbname, { page, limit: maxLimit });

  if (!resList.data.data || !resList.data.data.length) {
    console.warn('执行结束');
    loadData.field = false;
    return;
  }

  // 循环所有数据
  for (let i = 0; i < resList.data.data.length; i++) {
    const item = resList.data.data[i];

    const res = await getRepairDetail(dbname, item.id!);

    const str = res.data.content ?? '';
    if (!str) continue;

    const dataOpt: any = {};

    // 检查数据是否正常
    const imgDoms = str.match(/<img.*?src="(.*?)".*?\/?>/gi) ?? [];
    const imgSrcs = imgDoms.map((str: string) =>
      getAttrValByHtml(str, 'img', 'src')
    );
    const judge = imgSrcs.every((str: string) => /^\/upload/.test(str));

    // 判断所有路径通过检测，否则修改所有路径
    if (judge) continue;

    console.group('更新商品字段');
    console.log(
      `[Limit] - ${maxLimit} -- [Page] - ${page} -- [Current] - ${i + 1}`
    );
    console.log(`[ownId] - ${item.ownId}`);
    console.log(`[title] - ${item.title}`);
    console.log(`--------更新字段--------`);
    dataOpt.content = str;
    console.log(`[content - Raw] - ${str}`);
    imgSrcs.forEach((srcStr: string) => {
      dataOpt.content = dataOpt.content.replace(
        new RegExp('"' + srcStr),
        '"/upload/attachment/' + srcStr
      );
    });
    console.log(`[content - New] - ${dataOpt.content}`);
    console.groupEnd();

    try {
      await updateRepair(dbname, res.data.id!, dataOpt);
    } catch (error) {
      console.error('submitRepairFieldByContent', error);
      loadData.field = false;
      return;
    }
  }

  setTimeout(() => {
    submitRepairFieldByContent(page + 1);
  }, 2 * 1000);
};
</script>

<style lang="scss" scoped></style>
